import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

export interface Ticket {
  id: string;
  name: string;
  description: string;
  price: number;
  totalQuantity: number;
  availableQuantity: number;
  validFrom: string;
  validTo: string;
  status: 'active' | 'inactive' | 'sold_out';
  createdAt: string;
  updatedAt: string;
}

export interface UserTicket {
  id: string;
  userId: string;
  ticketId: string;
  quantity: number;
  purchaseDate: string;
  status: 'purchased' | 'used' | 'expired';
  orderId: string;
}

@Injectable()
export class TicketService {
  private readonly ticketsFile = path.join(process.cwd(), 'data', 'tickets.json');
  private readonly userTicketsFile = path.join(process.cwd(), 'data', 'user-tickets.json');

  constructor() {
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    if (!fs.existsSync(this.ticketsFile)) {
      fs.writeFileSync(this.ticketsFile, JSON.stringify([]));
    }

    if (!fs.existsSync(this.userTicketsFile)) {
      fs.writeFileSync(this.userTicketsFile, JSON.stringify([]));
    }
  }

  private readTickets(): Ticket[] {
    const data = fs.readFileSync(this.ticketsFile, 'utf8');
    return JSON.parse(data);
  }

  private writeTickets(tickets: Ticket[]): void {
    fs.writeFileSync(this.ticketsFile, JSON.stringify(tickets, null, 2));
  }

  private readUserTickets(): UserTicket[] {
    const data = fs.readFileSync(this.userTicketsFile, 'utf8');
    return JSON.parse(data);
  }

  private writeUserTickets(userTickets: UserTicket[]): void {
    fs.writeFileSync(this.userTicketsFile, JSON.stringify(userTickets, null, 2));
  }

  findAll(): Ticket[] {
    return this.readTickets();
  }

  findById(id: string): Ticket | undefined {
    const tickets = this.readTickets();
    return tickets.find(ticket => ticket.id === id);
  }

  create(ticketData: Omit<Ticket, 'id' | 'availableQuantity' | 'status' | 'createdAt' | 'updatedAt'>): Ticket {
    const tickets = this.readTickets();
    const newTicket: Ticket = {
      id: Date.now().toString(),
      ...ticketData,
      availableQuantity: ticketData.totalQuantity,
      status: 'active',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    tickets.push(newTicket);
    this.writeTickets(tickets);
    return newTicket;
  }

  update(id: string, ticketData: Partial<Omit<Ticket, 'id' | 'createdAt' | 'availableQuantity'>>): Ticket | null {
    const tickets = this.readTickets();
    const index = tickets.findIndex(ticket => ticket.id === id);
    if (index === -1) return null;
    
    tickets[index] = {
      ...tickets[index],
      ...ticketData,
      updatedAt: new Date().toISOString(),
    };
    
    // 更新状态
    if (tickets[index].availableQuantity === 0) {
      tickets[index].status = 'sold_out';
    }
    
    this.writeTickets(tickets);
    return tickets[index];
  }

  delete(id: string): boolean {
    const tickets = this.readTickets();
    const initialLength = tickets.length;
    const filteredTickets = tickets.filter(ticket => ticket.id !== id);
    this.writeTickets(filteredTickets);
    return filteredTickets.length !== initialLength;
  }

  purchaseTicket(userId: string, ticketId: string, quantity: number): UserTicket | null {
    const tickets = this.readTickets();
    const ticketIndex = tickets.findIndex(t => t.id === ticketId);
    
    if (ticketIndex === -1) return null;
    
    const ticket = tickets[ticketIndex];
    
    // 检查库存
    if (ticket.availableQuantity < quantity) {
      return null;
    }
    
    // 更新票数
    ticket.availableQuantity -= quantity;
    if (ticket.availableQuantity === 0) {
      ticket.status = 'sold_out';
    }
    tickets[ticketIndex] = ticket;
    this.writeTickets(tickets);
    
    // 创建用户票据记录
    const userTickets = this.readUserTickets();
    const newUserTicket: UserTicket = {
      id: Date.now().toString(),
      userId,
      ticketId,
      quantity,
      purchaseDate: new Date().toISOString(),
      status: 'purchased',
      orderId: `ORDER_${Date.now()}`,
    };
    
    userTickets.push(newUserTicket);
    this.writeUserTickets(userTickets);
    
    return newUserTicket;
  }

  getUserTickets(userId: string): UserTicket[] {
    const userTickets = this.readUserTickets();
    return userTickets.filter(ut => ut.userId === userId);
  }

  getTicketPurchases(ticketId: string): UserTicket[] {
    const userTickets = this.readUserTickets();
    return userTickets.filter(ut => ut.ticketId === ticketId);
  }
}